package com.ruoyi.web.controller.hazard;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.hazard.domain.vo.HazardInfoVo;
import com.ruoyi.system.service.ISysDeptService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.compress.utils.Lists;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.hazard.domain.HazardRiskWork;
import com.ruoyi.hazard.service.IHazardRiskWorkService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 作业风险Controller
 * 
 * @author ruoyi
 * @date 2025-10-25
 */
@RestController
@RequestMapping("/hazard/work")
public class HazardRiskWorkController extends BaseController
{
    @Autowired
    private IHazardRiskWorkService hazardRiskWorkService;
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询作业风险列表
     */
    @PreAuthorize("@ss.hasPermi('hazard:work:list')")
    @GetMapping("/list")
    public TableDataInfo list(HazardRiskWork hazardRiskWork)
    {
        startPage();
        List<HazardRiskWork> list = hazardRiskWorkService.selectHazardRiskWorkList(hazardRiskWork);
        if(!list.isEmpty()) {
            Map<Long, String> deptNameMap = sysDeptService.buildDeptNameMap(list.stream().map(HazardRiskWork::getDeptId).collect(Collectors.toList()));
            list.forEach(t -> { t.setDeptName(deptNameMap.get(t.getDeptId())); });
        }
        return getDataTable(list);
    }

    /**
     * 导出作业风险列表
     */
    @PreAuthorize("@ss.hasPermi('hazard:work:export')")
    @Log(title = "作业风险", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, HazardRiskWork hazardRiskWork)
    {
        List<HazardRiskWork> list = hazardRiskWorkService.selectHazardRiskWorkList(hazardRiskWork);
        if(!list.isEmpty()) {
            Map<Long, String> deptNameMap = sysDeptService.buildDeptNameMap(list.stream().map(HazardRiskWork::getDeptId).collect(Collectors.toList()));
            list.forEach(t -> { t.setDeptName(deptNameMap.get(t.getDeptId())); t.setResult(StringUtils.join(t.getConsequence(), ",")); });
        }
        ExcelUtil<HazardRiskWork> util = new ExcelUtil<HazardRiskWork>(HazardRiskWork.class);
        util.exportExcel(response, list, "作业风险数据");
    }

    /**
     * 获取作业风险详细信息
     */
    @PreAuthorize("@ss.hasPermi('hazard:work:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(hazardRiskWorkService.selectHazardRiskWorkById(id));
    }

    /**
     * 新增作业风险
     */
    @PreAuthorize("@ss.hasPermi('hazard:work:add')")
    @Log(title = "作业风险", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody HazardRiskWork hazardRiskWork)
    {
        hazardRiskWork.setCreateBy(SecurityUtils.getUsername());
        return toAjax(hazardRiskWorkService.insertHazardRiskWork(hazardRiskWork));
    }

    /**
     * 修改作业风险
     */
    @PreAuthorize("@ss.hasPermi('hazard:work:edit')")
    @Log(title = "作业风险", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody HazardRiskWork hazardRiskWork)
    {
        hazardRiskWork.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(hazardRiskWorkService.updateHazardRiskWork(hazardRiskWork));
    }

    /**
     * 删除作业风险
     */
    @PreAuthorize("@ss.hasPermi('hazard:work:remove')")
    @Log(title = "作业风险", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(hazardRiskWorkService.deleteHazardRiskWorkByIds(ids));
    }

    @ApiOperation("下载作业风险文件模板")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<HazardRiskWork> util = new ExcelUtil<HazardRiskWork>(HazardRiskWork.class);
        util.importTemplateExcel(response, "作业风险数据");
    }

    @PreAuthorize("@ss.hasPermi('hazard:work:import')")
    @ApiOperation("导入作业风险")
    @Log(title = "作业风险", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception{
        ExcelUtil<HazardRiskWork> util = new ExcelUtil<HazardRiskWork>(HazardRiskWork.class);
        List<HazardRiskWork> hazardRiskWorkVos = util.importExcel(file.getInputStream());
        hazardRiskWorkVos.stream().forEach(t -> t.setConsequence(StringUtils.isBlank(t.getResult()) ? Lists.newArrayList() : Arrays.asList(t.getResult().split(","))));
        String message = hazardRiskWorkService.importData(hazardRiskWorkVos, updateSupport);
        return success(message);
    }
}
